//
//  SiteListDownload.m
//  Alfresco
//
//  Created by Michael Muller on 10/21/09.
//  Copyright 2009 Michael J Muller. All rights reserved.
//

#import "SiteListDownload.h"
#import "SBJsonParser.h"
#import "Site.h"
#import "Utility.h"

@implementation SiteListDownload

@synthesize siteList;

- (void) dealloc {
	[siteList release];
	[super dealloc];
}

- (SiteListDownload *) initWithDelegate: (id <AsynchronousDownloadDelegate>) del {
	NSString *h = userPrefHostname();
	NSString *p = userPrefPort();
	NSString *w = userPrefWebApp();
	NSString *protocol = userPrefProtocol();
	
	NSString *urlStr = [[NSString alloc] initWithFormat:@"%@://%@:%@%@/service/api/sites?format=json", protocol, h, p, w];
	NSURL *u = [NSURL URLWithString:urlStr];
	[urlStr release];
	return (SiteListDownload *) [self initWithURL:u delegate:del];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

	// convert the data to a string
	NSString *str = [[NSString alloc] initWithData:self.data encoding:NSASCIIStringEncoding];
	
	// create a JSON parser
	SBJsonParser *jsonParser = [SBJsonParser new];  
	
	// parse the returned string
	NSArray *a = [jsonParser objectWithString:str];  

	// create an array to hold the site objects
	NSMutableArray *sites = [[NSMutableArray alloc] initWithCapacity:[a count]];

	// create a site object for each JSON entity
	for (NSDictionary *d in a) {
		Site *s = [[Site alloc] init];
		s.title = [d objectForKey:@"title"];
		s.node = [d objectForKey:@"node"];
		[sites addObject:s];
		[s release];
	}

	// sort the sites by title
	[sites sortUsingSelector:@selector(compareTitles:)];
	
	self.siteList = sites;

	// clean up; release objects to free memory
	[sites release];
	[jsonParser release];
	[str release];
	
	[super connectionDidFinishLoading:connection];
}

@end
